package com.itbac.j2cache.rabbitmq.consumer;

import com.google.gson.Gson;
import com.itbac.j2cache.client.J2CacheClient;
import com.itbac.j2cache.rabbitmq.config.J2CacheNoticeConfiguration;
import com.itbac.j2cache.rabbitmq.constants.RedisQueueName;
import com.itbac.j2cache.rabbitmq.message.J2CacheNotice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Import;
import org.springframework.messaging.handler.annotation.Payload;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @description 二级缓存MQ通知消费者
 *
 * @author itbac
 * @email 1218585258@qq.com
 * @date 2020/6/17
 */
@Configuration
@EnableAutoConfiguration
@Import(J2CacheNoticeConfiguration.class)
//监听的Queue,在J2CacheNoticeConfiguration中定义。
@RabbitListener(queues = "#{j2cacheNoticeQueue.name}")
@DependsOn(value = "caffeineConfig")
public class J2CacheNoticeConsumer {

    private static Logger logger = LoggerFactory.getLogger(J2CacheNoticeConsumer.class);

    @Resource
    private J2CacheClient j2CacheClient;
    @Resource
    private RedisQueueName redisQueueName;


    private Gson gson = new Gson();


    @RabbitHandler
    public void receive(@Payload String msg) {
        J2CacheNotice j2CacheNotice = gson.fromJson(msg, J2CacheNotice.class);
        if (null == j2CacheNotice) {
            return;
        }
        logger.info("J2CacheNoticeConsumer,收到消息：" + j2CacheNotice.toString() + ",当前节点：:" +
                redisQueueName.getName());
        //判断是否是本地消息
        if (!j2CacheNotice.isLocalNotice(redisQueueName.getName())) {
            logger.info("当前节点：{},收到其他节点通知删除本地缓存 keys {}",
                    redisQueueName.getName(), Arrays.toString(j2CacheNotice.getKeys()));
            if (j2CacheNotice.getOperator() == 0) {
                //消费者删除缓存，不发通知
                j2CacheClient.delLocalKeys(Arrays.asList(j2CacheNotice.getKeys()), false);
            }
            if (j2CacheNotice.getOperator() == 1) {
                //消费者删除缓存，不发通知
                j2CacheClient.delLocalAll(false);
            }
        } else {
            logger.info("当前节点：{},本地消息，不删除本地缓存。",
                    redisQueueName.getName());
        }
    }

}
